package com.cyy.common.utils;


import com.cyy.common.pojo.dto.CommentTreeDto;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class CommentUtils {


    /**
     * 评论和留言与其他树形结构不一样，只有两层：1.顶层，2.里面的互相回复，按照时间进行正序排序
     *
     * @param comments
     * @param node
     * @param visited
     * @param count
     */
    public static void generatorTreeAndCount(List<CommentTreeDto> comments, CommentTreeDto node, Set<Integer> visited, Integer count) {

        // 第一层处理
        // 在node的子级中添加一个children 然后返回这个 children
        List<CommentTreeDto> topList = handleTop(comments, node, visited, count);

        //二层处理 遍历一层
        for (CommentTreeDto topComment : topList) {
            List<CommentTreeDto> son = new ArrayList<>();
            handleChildren(comments, topComment, son, visited, count);
            son = son.stream().sorted((a, b) -> a.getCreateTime().compareTo(b.getCreateTime()))
                    .collect(Collectors.toList());
            topComment.setChildren(son);
        }


    }

    private static void handleChildren(List<CommentTreeDto> comments, CommentTreeDto topComment, List<CommentTreeDto> son, Set<Integer> visited, Integer count) {

        for (CommentTreeDto comment : comments) {
            if (visited.contains(comment.getId())) {
                continue;
            }
            if (comment.getParentId().equals(topComment.getId())) {
                visited.add(comment.getId());
                // 0:评论,1:点赞,2:踩
                if (comment.getType() == 0) {
                    son.add(comment);
                    count++;
                } else if (comment.getType() == 1) {
                    topComment.setLikeCount(topComment.getLikeCount() + 1);
                } else if (comment.getType() == 2) {
                    topComment.setDislikeCount(topComment.getDislikeCount() + 1);
                }
                handleChildren(comments, comment, son, visited, count);
            }
        }
    }


    /**
     * 一层处理
     *
     * @param comments
     * @param node
     * @param visited
     * @param count
     * @return
     */
    private static List<CommentTreeDto> handleTop(List<CommentTreeDto> comments, CommentTreeDto node, Set<Integer> visited, Integer count) {
        //查询第一层并按照时间进行倒序排列
        List<CommentTreeDto> topComments = new ArrayList<>();
        for (CommentTreeDto comment : comments) {
            if (comment.getParentId() == 0) {
                topComments.add(comment);
                visited.add(comment.getId());
                count++;
            }
        }
        topComments = topComments.stream()
                .sorted((a, b) -> a.getCreateTime().compareTo(b.getCreateTime()))
                .collect(Collectors.toList());
        node.setChildren(topComments);
        return topComments;
    }
}
